import store from '@/store'

axios.defaults.baseURL = config.baseUrl;
axios.defaults.timeout = 20000;
axios.defaults.withCredentials = true; //意思是携带cookie信息,保持session的一致性
axios.defaults.headers.post['Content-Type'] = 'application/json';

var closeWait = function(obj) {
	//如果存在params或data,获取_wait字段
	var _wait;
	if(obj.config && obj.config.params) {
		_wait = obj.config.params._wait;
	}
	if(obj.config && obj.config.data) {
		var data = obj.config.data;
		if(typeof data == "string") {
			data = JSON.parse(data);
		}
		_wait = data._wait;
	}
	if(_wait != null) {
		loading.close();
	}
}
var loading;
var openWait = function(config) {
	//如果参数中的_wait字段是true,则打开等待框,并把等待框的id存回_wait
	if(config.params && config.params._wait != null) {
		loading = tool.loading({
			text: config.params._wait,
			background: "rgba(0,0,0,0)"
		});
	}
	if(config.data && config.data._wait != null) {
		loading = tool.loading({
			text: config.data._wait,
			background: "rgba(0,0,0,0)"
		});
	}
}

//request 拦截器
axios.interceptors.request.use(
	config => {
		openWait(config);
		//携带头部token
		var token = tool.getItem(lsKey.token, true);
		config.headers['token'] = (token ? token[0] : null);
		
		return config;
	},
	error => {
		var message = "系统错误：" + error.message;
		tool.message({showClose: true, message: message, type: 'error'});
		return Promise.reject(message);
	}
);

var errorMsg = function(msg) {
	tool.message({
		showClose: true,
		message: msg,
		type: 'error'
	});
};

var noLogin = function(msg) {
//	tool.message({showClose: true, message: msg, type: 'warning'});
	//清除缓存
	store.commit("setUser", null);
	tool.removeItem(lsKey.token);
	
	//页面要求必须登录状态,则跳转到登录页
	if($route.meta.hasToken == true) {
		router.push({
			name:"登录",
			params: {fromPath : $route.path}
		});
	}
};

//response 拦截器
axios.interceptors.response.use(
	response => {
		//关闭等待框
		closeWait(response);
		var result = response.data;

		if(result.type) {
			return response;
		}

		//无异常,返回数据
		if(result.status == "success") {
			return result.data;
		}

		//处理系统异常
		switch(result.errorCode) {
			case 9999:
				errorMsg("系统异常：9999");
				break;
			case 401:
				noLogin("未登录或登录过期：401");
				break;
			case 1001:
				errorMsg("该记录已存在：1001");
				break;
			case 1002:
				errorMsg("用户权限不足：1002");
				break;
			case 1004:
				errorMsg("参数解析异常：1004");
				break;
			case 1008:
				errorMsg("当前校区异常：1008");
				break;
			default:
				errorMsg(result.data.result);
		}
		return Promise.reject(result.errorCode);
	},
	error => {
		//关闭等待框
		closeWait(error);
		var message = "系统错误：" + error.message;

		tool.message({
			showClose: true,
			message: message,
			type: 'error'
		});
		return Promise.reject(message);
	}
)

window.axios = axios;